# -*-coding:utf-8-*-

try:
    import xml.etree.cElementTree as ET
except ImportError:
    import xml.etree.ElementTree as ET


def read_profile_data(fname):
    profile = {}
    tree = ET.ElementTree(file=fname)
    profile.setdefault('class', [])
    for node in tree.getroot():
        if node.tag == 'class':
            clazz = {}
            clazz.setdefault("age", node.attrib['age'])
            clazz.setdefault("proportion", float(node.attrib['proportion']))
            groups = []
            # parse sub tree
            for child in node.getchildren():
                group = {}
                group.setdefault("temper", child.attrib['temper'])
                group.setdefault('sex', child.attrib['sex'])
                group.setdefault('population', float(child.attrib['population']))
                group.setdefault('types', [])
                group.setdefault("stop", float(child.attrib['stop']))
                for x in child.getchildren():
                    driver = {}
                    for key in x.attrib:
                        driver.setdefault(key, float(x.attrib[key]))
                    group['types'].append(driver)
                groups.append(group)
            clazz.setdefault("groups", groups)
            profile['class'].append(clazz)
    return profile

def test_read_profile_data():
    fname = "../../resources/profile.xml"
    profile = read_profile_data(fname)
    print(profile)

def read_routes_data(fname):
    trips = []
    tree = ET.ElementTree(file=fname)
    for node in tree.getroot():
        if node.tag == 'vehicle':
            trip = {}
            for key in node.attrib:
                trip.setdefault(key, node.attrib[key])
            trip.setdefault("route", node[0].attrib['edges'])
            trips.append(trip)
    return trips

def read_network_length(fname):
    tree = ET.ElementTree(file=fname)
    edges = {}
    for node in tree.getroot():
        if node.tag == 'edge':
            edges.setdefault(node.attrib['id'], float(node[0].attrib['length']))
    return edges

if __name__ == '__main__':
    test_read_profile_data()